#include "StdFIFO.h"
#include <SystemHearder.h>

StdFIFO::StdFIFO(const std::string &filepath, mode m)
{
    if(mkfifo(filepath.c_str(),S_IRUSR | S_IWUSR)<0 && errno != EEXIST)  
    {
        perror("creat fifo error");
        return;
    }
    
    this->fd = open(filepath.c_str(),(int)m);
    printf("fd : %d\n",fd);
    
    if(fd < 0)
    {
        perror("open fifo error");
        return;
    }
    this->m = m;
    this->FilePath = filepath;
}

StdFIFO::~StdFIFO()
{
    close(fd);
    std::string cmd = "rm -f "+this->FilePath;
    system(cmd.c_str());
}

std::string StdFIFO::Read(size_t size)
{
    if(m == mode::WriteOnly)
    {
        printf("当前是写权限,无法读");
        return {};
    }
    char* s = new char[size];

    read(this->fd,s,size);
    std::string result(s);
    delete []s;
    return result;
}

void StdFIFO::Write(const std::string &a)
{
    if(m == mode::ReadOnly)
    {
        printf("当前是读权限,无法写");
        return;
    }
    write(fd,a.c_str(),a.size());
}
